package com.exsun.ex1077.ui.activity.main

import android.Manifest
import android.annotation.SuppressLint
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.View
import androidx.lifecycle.viewModelScope
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.*
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.PermissionUtils
import com.drake.brv.utils.divider
import com.drake.brv.utils.linear
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.exsun.ex1077.R
import com.exsun.ex1077.app.Constant
import com.exsun.ex1077.databinding.ActivityMainBinding
import com.exsun.ex1077.network.entity.*
import com.exsun.ex1077.ui.activity.bounds.BoundsListActivity
import com.exsun.ex1077.ui.activity.mileage.MileageListActivity
import com.exsun.ex1077.ui.activity.mine.MineActivity
import com.exsun.ex1077.ui.activity.msg.MsgActivity
import com.exsun.ex1077.ui.activity.search.SearchActivity
import com.exsun.ex1077.ui.activity.vehicledetail.VehicleDetailActivity
import com.exsun.ex1077.ui.activity.vehiclelist.VehicleListActivity
import com.exsun.ex1077.ui.popup.MapMenuPopup
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.zhangping.amap.AMapHelper
import com.zhangping.amap.LocationHelper
import com.zhangping.amap.cluster.*
import com.zhangping.amap.extend.getLatLng
import com.zhangping.amap.extend.isSuccess
import com.zhangping.fastjetpack.base.BaseActivity
import com.zhangping.fastjetpack.callback.SimpleXPopupCallback
import com.zhangping.fastjetpack.extend.*
import com.zhangping.fastjetpack.extend.base.parseState
import com.zhangping.fastjetpack.extend.view.toDrawable
import com.zhangping.fastjetpack.extend.view.toView
import com.zhangping.fastjetpack.model.Permission
import com.zhangping.fastjetpack.network.upgrade.pgyer.PgyerCheckUpdate
import com.zhangping.fastjetpack.network.websocket.WebSocketManager
import com.zhangping.fastjetpack.ui.popup.RequestPermissionPopup
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.map_cluster.view.*
import kotlinx.android.synthetic.main.map_cluster_polygon_name.view.*
import kotlinx.android.synthetic.main.map_cluster_selected.view.*
import kotlinx.android.synthetic.main.map_main_marker_vehicleno.view.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.*
import kotlin.collections.ArrayList
import kotlin.concurrent.schedule

/**
 * 描述：主页
 * 作者：ZhangPing
 * 创建时间：2022/8/8 10:48
 */
class MainActivity: BaseActivity<MainViewModel, ActivityMainBinding>() {

    override fun title() = "未连接"
    override fun backIcon() = R.drawable.main_mine
    override fun enableDoubleBackExit() = true

    private lateinit var mapHelper: AMapHelper
    //地图聚合
    private var mClusterOverlay: ClusterOverlay? = null
    private val mBackDrawAbles: MutableMap<Int, Drawable> = mutableMapOf()
    //当前选中的车
    private var currentVehicle: MapVehicle? = null
    private var vehicleMarker: Marker? = null
    private var vehicleBubbleMarker: Marker? = null
    //车辆集合
    private var mapVehicleList: ArrayList<MapVehicle> = arrayListOf()
    private var onlineList: List<MapVehicle> = arrayListOf()
    private var offlineList: List<MapVehicle> = arrayListOf()
    private var customList: ArrayList<MapVehicle> = arrayListOf()
    private var boundsList: ArrayList<Bounds> = arrayListOf()
    private var boundsPolygonList: ArrayList<Polygon> = arrayListOf()
    private var boundsPolygonNameList: ArrayList<Marker> = arrayListOf()
    private var lineList: ArrayList<Bounds> = arrayListOf()
    private var linePolylineList: ArrayList<Polyline> = arrayListOf()
    private var linePolylineNameList: ArrayList<Marker> = arrayListOf()

    //从车辆搜索选择的车辆需要放大层级
    private var isFromSearch = false
    //是否来自定时刷新
    private var isFromTimingRefresh = false
    //地图定时刷新间隔
    private var timingRefreshInterval = 33 * 1000L
    //车牌气泡集合
    private val vehicleBubbleMap = mutableMapOf<String, Marker>()
    //当前地图层级
    private var currentMapZoom = 10.0F
    //显示车牌气泡的层级
    private val MAP_SHOW_BUBBLE_ZOOM = 14
    //地图画布第二次改变
    private var mapCameraDoubleChange = false
    //地图菜单弹窗
    private lateinit var mapMenuPopup: MapMenuPopup
    private lateinit var bottomSheet: BottomSheetBehavior<*>
    //首次定位
    private var isFirstLocation = true
    //菜单权限
    private var menuPermissions = arrayListOf<MenuTree>()

    @SuppressLint("ClickableViewAccessibility")
    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.vm = mViewModel
        super.initView(savedInstanceState)
        WebSocketManager.connect()
        mapHelper = AMapHelper(mapView.map).apply {
            bindLifecycle(lifecycle, mapView)
            hideLogo()
            applyStyle()
            applyCustomStyle(R.raw.style, R.raw.style_extra)
            moveMap()
        }
        mapHelper.map.apply {
            setOnMapClickListener {
                //隐藏面板
                mViewModel.showVehicleInfo.set(false)
                bottomSheetPeekHeightReset()
            }
            setOnPolylineClickListener {

            }
        }
        //动态计算车牌号可显示的最大宽度
        vehicleNo.maxWidth = screenWidth() - dp2px(80 + 16 + 30 + 24 + 28 + 65 + 22)
        search.setOnClickListener {
            toActivityForResult<SearchActivity>{ result ->
                if (result.resultCode != RESULT_OK) return@toActivityForResult
                val dvo = result.data!!.getStringExtra("dvo")
                mViewModel.showVehicleType.set(Constant.MAP_STATUS_ALL)
                mapVehicleList.firstOrNull { it.dvo ==  dvo}?.let {
                    isFromSearch = true
                    selectVehicle(it)
                }
            }
        }
        mapMenuPopup = XPopup.Builder(this)
            .maxHeight((screenHeight() * 0.75).toInt())
            .asCustom(MapMenuPopup(this, mapHelper, { map ->
                mViewModel.showVehicleType.set(Constant.MAP_STATUS_CUSTOM)
                val newList = mapVehicleList.filter {
                    map[it.objType]?.contains(it.onlineStatus) ?: false
                }
                customList.clear()
                customList.addAll(newList)
                if (currentVehicle != null && newList.count { it.dvo == currentVehicle!!.dvo } > 0){
                    currentVehicle = newList.first { it.dvo == currentVehicle!!.dvo }
                    selectVehicle(currentVehicle!!)
                }else{
                    cancelFollow()
                    updateMapUI(newList)
                }
            },{ showPolygon ->
                //显示多边形
                if (showPolygon) showBounds() else hideBounds()
            }, { showLine ->
                //显示线路
                if (showLine) showLine() else hideLine()
            })) as MapMenuPopup
        millageListView.linear().divider {
            setDivider(1, true)
            setColor(R.color.divider.toColorRes())
        }.setup {
            addType<MileageRank> { R.layout.item_main_millage }
        }
        millageMore.setOnClickListener {
            toActivity<MileageListActivity>()
        }
        mapMenu.setOnClickListener {
            mapMenuPopup.show()
            mViewModel.loadCheckObject()
        }
        myLocation.setOnClickListener {
            if (LocationHelper.hasLocationPermission()){
                mapHelper.moveToMyLocation()
            }else{
                requestPermission()
            }
        }
        vehicleInfo.setOnClickListener {
            toActivity<VehicleDetailActivity>(Bundle().apply {
                putSerializable("model", mViewModel.detailModel.get())
            })
        }
        video.setOnClickListener {
            mViewModel.detailModel.get()?.let {
                if (!it.isHasChannel() || !it.isOnlineA()) return@setOnClickListener
                toActivity<VehicleDetailActivity>(Bundle().apply {
                    putSerializable("model", it)
                    putBoolean("videoFirst", true)
                })
            }
        }
        findVehicle.setOnClickListener {
            mViewModel.detailModel.get()?.let{
                toActivity<FindVehicleActivity>(Bundle().apply {
                    putSerializable("model", it)
                })
            }
        }
        allBox.setOnClickListener {
            mViewModel.showVehicleType.set(Constant.MAP_STATUS_ALL)
            currentVehicle?.let { selectVehicle(it) } ?: updateMapUI(mapVehicleList)
            mapMenuPopup.resetMapMenuTagStatus()
        }
        onlineBox.setOnClickListener {
            mViewModel.showVehicleType.set(Constant.MAP_STATUS_ONLINE)
            if (currentVehicle != null && currentVehicle!!.isOnlineA()){
                selectVehicle(currentVehicle!!)
            }else{
                cancelFollow()
                updateMapUI(onlineList)
            }
            mapMenuPopup.resetMapMenuTagStatus()
        }
        offlineBox.setOnClickListener {
            mViewModel.showVehicleType.set(Constant.MAP_STATUS_OFFLINE)
            if (currentVehicle != null && !currentVehicle!!.isOnlineA()){
                selectVehicle(currentVehicle!!)
            }else{
                cancelFollow()
                updateMapUI(offlineList)
            }
            mapMenuPopup.resetMapMenuTagStatus()
        }
        menu.setOnClickListener {
            showMenu()
        }
        bottomSheet = BottomSheetBehavior.from(bottomView)
        bottomSheetPeekHeightReset()
        //检查更新
        PgyerCheckUpdate.checkUpdate(this)
        //检查是否需要直接跳转到添加设备页面
        val toAddDevicePage = intent.getBooleanExtra("toAddDevicePage", false)
        if (toAddDevicePage) toActivity<VehicleListActivity>()
        mViewModel.apply {
            loadMenuPermission()
            loadMapData(true)
            loadMileageRank()
            loadCheckObject()
            loadBoundsData()
            loadVideoCloseTime()
        }
        //定时刷新地图数据
        timingRefreshMapData()
    }

    private fun requestPermission() {
        RequestPermissionPopup.create(this, arrayListOf(Permission("地理位置", "仅用于获取位置信息，提供精准车辆查询服务", arrayListOf(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        ))), true) { isAllGranted, granted, deniedForever, denied ->
            if (!isAllGranted) {
                "定位权限申请被拒绝!".showToast()
                return@create
            }
            LocationHelper.startLocation(60 * 1000)
        }.show()
    }

    /**
     * 在地图上显示围栏
     */
    private fun showBounds(){
        hideBounds()
        mViewModel.viewModelScope.launch(Dispatchers.Default) {
            boundsList.forEach{
                //添加围栏
                val polygon = mapHelper.map.addPolygon(PolygonOptions()
                    .strokeWidth(0F)
                    .fillColor(R.color.color_3C7BF8_30.toColorRes())
                    .addAll(it.getBoundsLatLngList()))
                boundsPolygonList.add(polygon)
                //添加围栏名称
                val view = R.layout.map_cluster_polygon_name.toView()
                view.name.text = it.name
                val polygonName = mapHelper.map.addMarker(MarkerOptions()
                    .position(it.getCenterLatLng())
                    .anchor(0.5F, 0.5F)
                    .icon(BitmapDescriptorFactory.fromView(view)))
                boundsPolygonNameList.add(polygonName)
            }
        }
    }

    /**
     * 隐藏围栏
     */
    private fun hideBounds(){
        mViewModel.viewModelScope.launch(Dispatchers.Default) {
            boundsPolygonList.apply {
            forEach { it.remove() }
            clear()
        }
        boundsPolygonNameList.apply {
                forEach { it.remove() }
                clear()
            }
        }
    }

    /**
     * 在地图上显示线路
     */
    private fun showLine(){
        hideLine()
        mViewModel.viewModelScope.launch(Dispatchers.Default) {
            lineList.forEach{
                val polyline = mapHelper.map.addPolyline(PolylineOptions()
                    .width(dp2px(3).toFloat())
                    .color(R.color.color_00CD9C.toColorRes())
                    .addAll(it.getBoundsLatLngList()))
                linePolylineList.add(polyline)
                //添加线路名称
                val view = R.layout.map_cluster_polygon_name.toView()
                view.name.text = it.name
                val lineName = mapHelper.map.addMarker(MarkerOptions()
                    .position(it.getCenterLatLng())
                    .anchor(0.5F, 0.5F)
                    .icon(BitmapDescriptorFactory.fromView(view)))
                linePolylineNameList.add(lineName)
            }
        }
    }

    /**
     * 隐藏线路
     */
    private fun hideLine(){
        mViewModel.viewModelScope.launch(Dispatchers.Default) {
            linePolylineList.apply {
                forEach { it.remove() }
                clear()
            }
            linePolylineNameList.apply {
                forEach { it.remove() }
                clear()
            }
        }
    }

    /**
     * 取消跟踪
     */
    private fun cancelFollow() {
        mViewModel.apply {
            if (showVehicleInfo.get()){
                showVehicleInfo.set(false)
                currentVehicle = null
                detailModel.set(null)
                bottomSheetPeekHeightReset()
            }
        }
    }

    /**
     * 定时刷新地图数据
     */
    private fun timingRefreshMapData(){
        Timer().schedule(timingRefreshInterval, timingRefreshInterval){
            mViewModel.loadMapData()
            mViewModel.loadBoundsData()
        }
    }

    /**
     * 显示功能菜单
     */
    private fun showMenu(){
        if (menuPermissions.isEmpty()) return
        menu.setImageResource(R.drawable.main_menu_checked)
        XPopup.Builder(this)
            .atView(menu)
            .offsetX(dp2px(10))
            .isLightStatusBar(true)
            .hasShadowBg(false)
            .setPopupCallback(object : SimpleXPopupCallback(){
                override fun onDismiss(popupView: BasePopupView) {
                    menu.setImageResource(R.drawable.main_menu)
                }
            })
            .asAttachList(menuPermissions.map { it.label }.toTypedArray(), null) { position, text ->
                val model = menuPermissions[position]
                val menuPermission = model.toMenuPermission()
                when(model.perms){
                    "app:equipment:list" -> {
                        toActivity<VehicleListActivity>(Bundle().apply {
                            putInt("queryStatus", VehicleListActivity.STATUS_ALL)
                            putSerializable("menuPermission", menuPermission)
                        })
                    }
                    "app:electricFence:list" -> {
                        toActivity<BoundsListActivity>(Bundle().apply {
                            putSerializable("menuPermission", menuPermission)
                        })
                    }
                    "app:mileageStatistics:list" -> {
                      toActivity<MileageListActivity>(Bundle().apply {
                          putSerializable("menuPermission", menuPermission)
                      })
                    }
                }
            }.show()
    }

    /**
     * 抽屉菜单恢复初始高度
     */
    private fun bottomSheetPeekHeightReset(){
        bottomSheet.peekHeight = dp2px(118)
    }

    /**
     * 抽屉菜单设置为选中车辆时的高度
     */
    private fun bottomSheetPeekHeightUpdate(){
        bottomSheet.peekHeight = dp2px(238)
    }

    override fun onBackClick(view: View) {
        toActivity<MineActivity>()
    }

    override fun onActionClick(view: View) {
        toActivity<MsgActivity>()
    }

    /**
     * 添加节点到地图
     * @param list
     */
    private fun updateMapUI(list: List<ClusterItem>?) {
        val aMap = mapView.map.apply { clear() }
        mapHelper.addMyLocationMarker()
        mClusterOverlay = ClusterOverlay(aMap, list, ConvertUtils.dp2px(30F), activity)
        mClusterOverlay!!.setClusterRenderer(object : SimpleClusterRender(){
            override fun getDrawAble(clusterNum: Int, cluster: Cluster): Drawable {
                val drawable: Drawable? = when {
                    clusterNum == 1 -> {
                        val model = cluster.clusterItems[0].getModel<MapVehicle>()
                        val view = R.layout.map_cluster.toView()
                        view.bg.setBackgroundResource(model.onlineStatusBgDrawableId())
                        view.icon.setImageResource("object_${model.objIcon}".toDrawableId())
                        view.toDrawable()
                    }
                    else -> {
                        var bitmapDrawable = mBackDrawAbles[1]
                        if (bitmapDrawable == null) {
                            bitmapDrawable = BitmapDrawable(null, drawCircle(50, R.color.color_67D5C8))
                            mBackDrawAbles[1] = bitmapDrawable
                        }
                        mBackDrawAbles[1]
                    }
                }
                return drawable!!
            }

            override fun onCreateMarker(clusterNum: Int, cluster: Cluster, marker: Marker) {
                if (clusterNum > 1 || currentMapZoom < MAP_SHOW_BUBBLE_ZOOM) return
            }

            override fun onCameraChangeFinish(cameraPosition: CameraPosition) {
                currentMapZoom = mapHelper.map.cameraPosition.zoom
                //移除已添加的车牌
                vehicleBubbleMarker?.isVisible = currentMapZoom >= MAP_SHOW_BUBBLE_ZOOM
            }

            override fun onClusterAddMarkerFinish(markerList: MutableList<Marker>) {
                if (mapCameraDoubleChange){
                    mapCameraDoubleChange = false
                    return
                }
                if (currentMapZoom < MAP_SHOW_BUBBLE_ZOOM){
                    vehicleBubbleMap.values.forEach { it.remove() }
                    vehicleBubbleMap.clear()
                    return
                }
                if (markerList.isNullOrEmpty()) return
                val notNeedRemoveBubbleVehicleNo = arrayListOf<String>()
                markerList.forEach {
                    val itemList = (it.`object` as Cluster).clusterItems
                    if (itemList.size == 1){
                        //是单车Marker
                        val model = itemList[0].getModel<MapVehicle>()
                        if (!vehicleBubbleMap.keys.contains(model.vehicleNo)){
                            //添加车牌气泡
                            val view = R.layout.map_main_marker_vehicleno.toView()
                            view.title.text = model.vehicleNo
                            val vehicleNoMarker = mapHelper.map.addMarker(MarkerOptions()
                                .anchor(0.0F, 0.5F)
                                .position(it.position)
                                .icon(BitmapDescriptorFactory.fromView(view)))
                            vehicleNoMarker.isClickable = false
                            vehicleBubbleMap[model.vehicleNo ?: ""] = vehicleNoMarker
                        }
                        notNeedRemoveBubbleVehicleNo.add(model.vehicleNo ?: "")
                    }
                }
                ArrayList(vehicleBubbleMap.keys).forEach {
                    if (!notNeedRemoveBubbleVehicleNo.contains(it)){
                        vehicleBubbleMap[it]?.remove()
                        vehicleBubbleMap.remove(it)
                    }
                }
            }
        })
        mClusterOverlay!!.setOnClusterClickListener(object : ClusterClickListener {
            override fun onClick(marker: Marker, clusterItems: MutableList<ClusterItem>) {
                if (clusterItems.size == 1) {
                    val vehicle = clusterItems[0].getModel<MapVehicle>()
                    selectVehicle(vehicle)
                    return
                }
                val builder = LatLngBounds.Builder()
                for (clusterItem in clusterItems) {
                    builder.include(clusterItem.position)
                }
                val latLngBounds = builder.build()
                aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, dp2px(50)), 1000, null)
            }

            override fun onOtherClick(marker: Marker) {
                if (marker == vehicleMarker){
                    //显示车辆信息面板
                    bottomSheetPeekHeightUpdate()
                    mViewModel.showVehicleInfo.set(true)
                }
            }
        })
        if (mapMenuPopup.isShowBounds()) showBounds() else hideBounds()
        if (mapMenuPopup.isShowLine()) showLine() else hideLine()
    }

    /**
     * 选择车辆
     */
    private fun selectVehicle(vehicle: MapVehicle, isFromTimingRefresh: Boolean = false){
        this.isFromTimingRefresh = isFromTimingRefresh
        vehicleBubbleMap.clear()
        val list = getMapDataListByShowType()
        //将目标点从聚合中移除，更新地图
        updateMapUI(ArrayList(list).apply {
            remove(vehicle)
        })
        //单独添加目标到地图上
        val view = R.layout.map_cluster_selected.toView()
        view.iv_bg.setImageResource("object_${vehicle.objIcon}".toDrawableId())
        view.iv_arrow.rotation = vehicle.dre.toFloat()
        vehicleMarker = mapHelper.map.addMarker(MarkerOptions()
            .anchor(0.5F, 0.5F)
            .position(vehicle.position)
            .zIndex(999F)
            .icon(BitmapDescriptorFactory.fromView(view))
        )
        //添加车牌气泡
        val bubbleView = R.layout.map_main_marker_vehicleno.toView()
        bubbleView.title.text = vehicle.vehicleNo
        vehicleBubbleMarker = mapHelper.map.addMarker(MarkerOptions()
            .anchor(0.0F, 0.5F)
            .position(vehicle.position)
            .zIndex(999F)
            .visible(mapHelper.map.cameraPosition.zoom >= MAP_SHOW_BUBBLE_ZOOM)
            .icon(BitmapDescriptorFactory.fromView(bubbleView))).apply { isClickable = false }
        currentVehicle = vehicle
        mViewModel.detailModel.set(vehicle)
        //移动地图到目标位置
        mapCameraDoubleChange = true
        if (!isFromTimingRefresh) {
            mViewModel.loadVehicleData(vehicle.dvo)
            mapHelper.animateMap(vehicle.position)
        }
    }

    /**
     * 根据状态显示类型筛选数据
     */
    private fun getMapDataListByShowType(): List<MapVehicle> {
        return when(mViewModel.showVehicleType.get()){
            Constant.MAP_STATUS_ALL -> mapVehicleList
            Constant.MAP_STATUS_ONLINE -> onlineList
            Constant.MAP_STATUS_OFFLINE -> offlineList
            else -> customList
        }
    }

    override fun onResume() {
        super.onResume()
        if (WebSocketManager.isConnected()){
            mViewModel.title.set("首页")
        }
        startVehicleTrackFromSocket()
        mViewModel.apply {
            loadUnReadMsgCount()
            loadMileageRank()
        }
    }

    override fun onPause() {
        stopSocket()
        super.onPause()
    }

    override fun createObserver() {
        super.createObserver()
        LocationHelper.locationLiveData.observe(this){
            if (!it.isSuccess()) return@observe
            if (isFirstLocation){
                isFirstLocation = false
                mapHelper.moveMap(it.getLatLng())
                mapHelper.addMyLocationMarker()
            }else{
                mapHelper.myLocationMarker?.apply {
                    position = it.getLatLng()
                    rotateAngle = it.bearing
                }
            }
        }
        mViewModel.apply {
            menuPermissionResult.observe(this@MainActivity){
                parseState(it, {
                    menuPermissions.addAll(it)
                })
            }
            mapVehicleListResult.observe(this@MainActivity){
                parseState(it, {
                    if (it == null) return@parseState
                    mapVehicleList.clear()
                    mapVehicleList.addAll(it.list ?: emptyList())
                    online.text = it.onlineCount.toString()
                    offline.text = it.offlineCount.toString()
                    all.text = (it.onlineCount + it.offlineCount).toString()
                    onlineList = mapVehicleList.filter { it.isOnlineA() }
                    offlineList = mapVehicleList.filter { !it.isOnlineA() }
                    if (currentVehicle != null && mapVehicleList.count{ it.dvo == currentVehicle!!.dvo } > 0){
                        //此时对象地址已不一致，需要重新绑定对象
                        currentVehicle = mapVehicleList.first{ it.dvo == currentVehicle!!.dvo }
                        selectVehicle(currentVehicle!!, true)
                    }else{
                        updateMapUI(getMapDataListByShowType())
                    }
                })
            }
            mapVehicleGpsResult.observe(this@MainActivity){
                parseState(it, {
                    if (it == null || detailModel.get() == null || it.dvo != detailModel.get()!!.dvo) return@parseState
                    detailModel.get()!!.apply {
                        updateData(it)
                        detailModel.notifyChange()
                        updateVehicleMapMarker(lat, lng, dre)
                        bottomSheetPeekHeightUpdate()
                        showVehicleInfo.set(true)
                        if (isFromSearch){
                            isFromSearch = false
                            mapHelper.animateMap(position, AMapHelper.MAP_LEVEL_DETAIL)
                        }else{
                            mapHelper.animateMap(position)
                        }
                        startVehicleTrackFromSocket()
                    }
                })
            }
            mapMileageRankResult.observe(this@MainActivity){
                parseState(it, {
                    it.forEachIndexed { index, mileageRank -> mileageRank.rank = index + 1 }
                    millageListView.models = it
                })

            }
            objectTypeResult.observe(this@MainActivity){
                parseState(it, {
                    mapMenuPopup.setObjectType(ArrayList(it))
                })
            }
            mapBoundsResult.observe(this@MainActivity){
                parseState(it, {
                    boundsList.apply {
                        clear()
                        addAll(it.filter { it.type == Constant.BOUNDS_TYPE_POLYGON })
                    }
                    lineList.apply {
                        clear()
                        addAll(it.filter { it.type == Constant.BOUNDS_TYPE_LINE })
                    }
                })
            }
        }
        WebSocketManager.apply {
            connectStateLiveData.observeInActivity(this@MainActivity){
                when (it){
                    STATE_OPEN -> {
                        mViewModel.title.set("首页")
                        startVehicleTrackFromSocket()
                    }
                    STATE_CONNECTING -> {
                        mViewModel.title.set("连接中...")
                    }
                    STATE_CLOSE -> {
                        mViewModel.title.set("未连接")
                    }
                }
            }
            dataLiveData.observeInActivity(this@MainActivity){
                if (it.isNullOrEmpty()) return@observeInActivity
                val socketModel = it.toModel<VehicleTrackSocket>()
                val detailModel = mViewModel.detailModel.get()
                if (socketModel == null || detailModel == null || socketModel.dvo != detailModel.dvo) return@observeInActivity
                socketModel.wgs84ToGcj02()
                detailModel.apply {
                    lat = socketModel.lat
                    lng = socketModel.lng
                    gdt = socketModel.gdt
                    dre = socketModel.dre
                    location = socketModel.poi?.ars ?: ""
                    isOnline = if (socketModel.isVehicleOnline()) 1 else 0
                }
                mViewModel.detailModel.set(detailModel)
                mViewModel.detailModel.notifyChange()
                updateVehicleMapMarker(socketModel.lat, socketModel.lng, socketModel.dre)
            }
        }
    }

    /**
     * 更新当前选中车辆地图图标数据
     */
    private fun updateVehicleMapMarker(lat: Double = 0.0, lng: Double = 0.0, dre: Int = 0){
        //更新当前车辆经纬度
        if (vehicleMarker != null && currentVehicle != null){
            currentVehicle!!.let {
                it.lat = lat
                it.lng = lng
                it.dre = dre
            }
            vehicleMarker!!.position = currentVehicle?.position
            val view = R.layout.map_cluster_selected.toView()
            view.iv_bg.setImageResource("object_${currentVehicle!!.objIcon}".toDrawableId())
            view.iv_arrow.rotation = dre.toFloat()
            vehicleMarker!!.setIcon(BitmapDescriptorFactory.fromView(view))
        }
        vehicleBubbleMarker?.position = currentVehicle?.position
    }

    /**
     * 开始从Socket读取车辆信息
     */
    private fun startVehicleTrackFromSocket(){
        mViewModel.viewModelScope.launch {
            delay(1000)
            mViewModel.detailModel.get()?.let {
                WebSocketManager.sendMsg("type=2&dvo=${it.dvo}")
            }
        }
    }

    /**
     * 停止从Socket获取信息
     */
    private fun stopSocket(){
        WebSocketManager.sendMsg("type=2&dvo=0")
    }

    override fun onDestroy() {
        LocationHelper.onDestroy()
        super.onDestroy()
    }

}